package com.dily.study.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dily.study.user.entity.Permission;
import com.dily.study.user.entity.dto.RolePermission;
import com.dily.study.user.mapper.RolePermissionMapper;
import com.dily.study.user.entity.Role;
import com.dily.study.user.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Date: 2022-06-13 星期一
 * Time: 16:52
 * Author: Dily_Su
 * Remark:
 */
@Service
public class PermissionService extends ServiceImpl<PermissionMapper, Permission> {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private RoleService roleService;

    /**
     * 根据角色Id 查询权限列表
     *
     * @param userId 角色ID
     * @return permissions
     */
    public Set<Permission> getPermissionsByUserId(long userId) {
        Set<Permission> permissions  = new HashSet<>();
        Set<Role> roles = roleService.getRolesByUserId(userId);
        roles.forEach(r -> {
            List<RolePermission> rolePermissions = rolePermissionMapper.selectList(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId, r.getId()));
            rolePermissions.forEach(e -> permissions.add(this.getById(e.getPermissionId())));
        });
        return permissions;
    }
}
